<template>
    <div class="login">
        <div class="login-con">
            <!-- 顶部切换 -->
            <ul class="menu-tab">
                <li v-for="item in menuData" :key="item.id" :class="{ current: item.current }" @click="clickMenu(item)">
                    {{ item.txt }}
                </li>
            </ul>
            <!-- 表单部分 -->
            <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm">
                <!-- 修改提示文字 并且修改type类型 与v-model绑定的数据 并且添加类名-->
                <el-form-item prop="username" class="item-from">
                    <label for="username">邮箱</label>
                    <el-input v-model="ruleForm.username" type="text" autocomplete="off" />
                </el-form-item>
                <el-form-item prop="password" class="item-from">
                    <label for="password">密码</label>
                    <el-input id="password" type="password" v-model="ruleForm.password" autocomplete="off" minlength="6"
                        maxlength="20"></el-input>
                </el-form-item>

                <el-form-item prop="passwords" class="item-from" v-show="model === 'register'">
                    <label>重复密码</label>
                    <el-input type="password" v-model="ruleForm.passwords" autocomplete="off" minlength="6"
                        maxlength="20"></el-input>
                </el-form-item>
                <!-- 设置按钮 -->
                <el-button @click="submitForm(ruleFormRef)" type="danger" class="login-btn block" :disabled="btnbool">{{
                        model === "login" ?
                            "登录" : "注册"
                }}</el-button>
            </el-form>
            <!-- 表单部分 -->
        </div>
    </div>
</template>
  
<script lang="ts" setup>
import { onMounted, reactive, ref, watch } from "vue";
import { ElButton, ElForm, ElFormItem, ElInput, ElMessage, FormInstance } from "element-plus";
// 引用验证工具库
import * as verification from "../../util/verfifcation.js"
import link from "../../api/link.js";
import apiUrl from "../../api/url.js";
import useMd5 from "../../hooks/index.js"
import { useRouter } from "vue-router";



// 1.创建一个变量用来控制按钮是否能点击
let btnbool = ref(true)
//声明路由
let router = useRouter()

const menuData = reactive([
    { txt: "登录", current: true, type: "login" },
    { txt: "注册", current: false, type: "register" },
]);
const model = ref("login");

onMounted(() => {

    console.log(process.env.VUE_APP_API);
});
const clickMenu = (data: any) => {
    menuData.forEach((elem) => {
        elem.current = false;
    });
    // 高光
    data.current = true;
    // 修改模块值
    model.value = data.type;
};
//表单验证开始
const ruleFormRef = ref<FormInstance>();
const checkAge = (rule: any, value: any, callback: any) => {
    if (!value) {
        return callback(new Error("Please input the age"));
    }
    setTimeout(() => {
        if (!Number.isInteger(value)) {
            callback(new Error("Please input digits"));
        } else {
            if (value < 18) {
                callback(new Error("Age must be greater than 18"));
            } else {
                callback();
            }
        }
    }, 1000);
};
//邮箱验证开始
const checkUser = (rule: any, value: any, callback: any) => {
    // 创建邮箱正则来进行邮箱格式校验
    // let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    if (!value) {
        return callback(new Error("邮箱不能为空！！"));

    } else if (verification.verificationEmail(value)) {
        return callback(new Error("邮箱格式有误！！"));

    } else {
        callback();
    }
};
//邮箱验证结束
//密码验证开始
const validatePass = (rule: any, value: any, callback: any) => {
    // let reg = /^(?!\D+$)(?![^a-zA-Z]+$)\S{6,15}$/;// 验证密码 6至15位的字母+数字 
    if (value === "") {
        callback(new Error("密码不能为空"));
    } else if (verification.verificationPwd(value)) {
        callback(new Error("密码格式有误!6至15位的字母+数字"));
    } else {
        callback();
    }
};
//密码验证结束
//重复密码验证开始
const validatePass2 = (rule: any, value: any, callback: any) => {
    // 因为登录没有重复密码 所以在登录的时候跳过
    if (model.value === 'login') { callback(); }
    if (value === "") {
        callback(new Error("重复密码不能为空"));
    } else if (value !== ruleForm.password) {
        callback(new Error("两次密码必须相同"));
    } else {
        callback();
    }
};
//重复密码验证结束

const ruleForm = reactive({
    username: "",
    password: "",
    passwords: "",
});




watch(ruleForm, (newval) => {
    // console.log(newval)
    // 判断是登录还是注册
    if (model.value == 'login') {
        // 登录
        if (newval.username != "" && newval.password != "") {
            btnbool.value = false
        } else {
            btnbool.value = true
        }
    } else {
        // 注册
        if (newval.username != "" && newval.password != "" && newval.passwords != "") {
            btnbool.value = false
        } else {
            btnbool.value = true
        }
    }
})


// 这里是设置设置 以何种方式触发 表单验证 默认是blur失去焦点验证
// 当触发了blur事件后就会调用前面的 函数从而进行表单验证
const rules = reactive({
    password: [{ validator: validatePass, trigger: "blur" }],
    passwords: [{ validator: validatePass2, trigger: "blur" }],
    username: [{ validator: checkUser, trigger: "blur" }],//修改名字 并且修改上面的函数名
});

const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            // 判断是登录还是注册
            if (model.value == "login") {
                console.log("登录");
                //发送登录请求
                link(`/register?uname=${ruleForm.username}&pwd=${useMd5(ruleForm.password).value}`, "get").then((ok:any) => {
                    // console.log(ok)
                    let { data } = ok;//解构出数据
                    // 判断data长度不为0登录成功
                    if (data.length != 0) {
                        console.log("登录成功")
                        //编程式导航跳转
                        router.push('/home')
                    } else {
                        console.log("登录失败")
                    }
                })
            } else {
                // 把要发送的数据拼装成一个对象
                let data = {
                    uname: ruleForm.username,
                    pwd: useMd5(ruleForm.password).value,
                };

                link(apiUrl.register, "POST", data).then((ok:any) => {
                    // 判断数据是否为空 不为空表示注册成功

                    let { data } = ok
                    // 转成成数组判断长度即可知道对象是否为空
                    if (Object.keys(data).length !== 0) {
                        ElMessage("注册成功");
                        //  把输入框的内容切换到登录
                        model.value = "login"
                        // 把上面的切换按钮编程登录
                        // 先把所有的的控制切换的变量编程false
                        menuData.forEach((elem) => {
                            elem.current = false;
                        });
                        // 在吧登录的编程true
                        menuData[0].current = true;
                    } else {
                        ElMessage.error("注册失败");
                    }
                });
            }
        } else {
            console.log("error submit!");
            return false;
        }
    });
};
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    formEl.resetFields();
};
//表单验证结束
</script>
<style lang="scss">
.login {
    background-color: #000066; //深蓝色
    height: 100%;
}

html,
body,
#app {
    //设置页面100%高
    height: 100%;
}

// 设置切换样式开始
.login-wrap {
    width: 330px;
    margin: auto;
}

.menu-tab {
    text-align: center;

    li {
        display: inline-block;
        width: 88px;
        line-height: 36px;
        font-size: 14px;
        color: #fff;
        border-radius: 2px;
        cursor: pointer;
    }

    .current {
        background-color: rgba(255, 255, 255, 0.5); //白色半透明
    }
}

// 设置切换样式结束

// 表单样式
.demo-ruleForm {
    width: 30%;
    margin: 50px auto;

    label {
        display: block;
        margin-bottom: 3px;
        font-size: 14px;
        color: #fff;
    }

    .item-from {
        margin-bottom: 13px;
    }

    .block {
        display: block;
        width: 100%;
    }

    .login-btn {
        margin-top: 19px;
    }
}

// 表单样式
</style>